<?php

namespace App\Services;

use App\Models\ZPituitaryManageDrugs;
use App\Models\ZPituitaryManageDrugsRecords;
use App\Models\ZPituitaryDrugType;
use App\Models\ZPituitaryDrug;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class DrugService {

    public function __construct() {
        
    }

    //用药列表 (选择列表)
    public function getDrugs($mode) {
        $data = [];
        $results = ZPituitaryDrugType::getAll($mode);
        foreach ($results as $item) {
            $data[$item['type_category']][$item['type_id']]['name'] = $item['type_name'];
            $data[$item['type_category']][$item['type_id']]['children'][] = $item;
        }

        $data = array_map(function ($v) {
            return array_values($v);
        }, $data);

        return $data;
    }

    public function getUsedDrugs($usedId,$mode) {
        return ZPituitaryManageDrugs::query()->from('z_pituitary_manage_drugs as nd')
                        ->select('nd.drug_id', 'nd.drug_alias', 'd.type_id')
                        ->leftJoin('z_pituitary_drug as d', 'd.id', '=', 'nd.drug_id')
                        ->leftJoin('z_pituitary_drug_type as t', 'd.type_id', '=', 't.id')
                        ->where("nd.user_id", $usedId)->where("t.pid", $mode)->where("nd.is_used", 1)->where("nd.is_deleted", 0)->get();
    }

    //获取用户的正在使用的用药
    //获取用药状态
    public function getDrugDetailByUserId($usedId, $drugId, $drugAlias) {
        if (in_array($drugId, [202,203,204,205])) {
            return ZPituitaryManageDrugs::where("user_id", $usedId)->where("drug_id", $drugId)->where("drug_alias", $drugAlias)->where("is_deleted", 0)->first();
        } else {
            return ZPituitaryManageDrugs::where("user_id", $usedId)->where("drug_id", $drugId)->where("is_deleted", 0)->first();
        }
    }

    //新增 或者 补填用药 （新增）
    public function insertGetId($table, $data) {
        $column = Schema::getColumnListing($table);
        $arr = array_intersect_key($data, array_flip($column));
        $date = date("Y-m-d H:i:s");
        $arr["created_at"] = $date;
        $arr["updated_at"] = $date;
        if (isset($arr["id"])) {
            unset($arr["id"]);
        }
        return DB::table($table)->insertGetId($arr);
    }

    // 重新启用用药 （更新）
    public function updateGetId($table, $data, $id, $field = "id") {
        $column = Schema::getColumnListing($table);
        $arr = array_intersect_key($data, array_flip($column));
        $date = date("Y-m-d H:i:s");
        $arr["updated_at"] = $date;
        if (isset($arr["id"])) {
            unset($arr["id"]);
        }
        DB::table($table)->where($field, $id)->update($arr);
        return $id;
    }

    //取用药最新的一条 不含删除
    public function getLastDrugRecord($maxId, $mmcDrugId) {
        return ZPituitaryManageDrugsRecords::where("pituitary_drugs_id", $mmcDrugId)->where("id", "<>", $maxId)->where("is_deleted", 0)->orderBy("id", "desc")->first();
    }

    //返回用药详细（调整/停药/删除使用）
    public function getRecordDetailById($id) {
        return ZPituitaryManageDrugs::where("id", $id)->where("is_deleted", 0)->first();
    }

    //获取用药记录详细
    public function getDrugRecord($id) {
        return ZPituitaryManageDrugsRecords::where("id", $id)->where("is_deleted", 0)->first();
    }

    //删除用药里面 最后一条记录
    public function getDrugRelationId($rid) {
        return ZPituitaryManageDrugs::where("relation_records_id", $rid)->where("is_deleted", 0)->first();
    }

    //点击查看用药列表
    public function getDrugRecordsListTotal($id) {
        return ZPituitaryManageDrugsRecords::where("pituitary_drugs_id", $id)->where("is_deleted", 0)->count();
    }

    //点击查看用药列表
    public function getDrugRecordsList($id, $pageNo = 0, $pageSize = 10) {
        $offset = $pageNo * $pageSize;
        return ZPituitaryManageDrugsRecords::query()
                        ->from('z_pituitary_manage_drugs_records as ndr')
                        ->leftJoin('z_pituitary_manage_drugs as nd', 'nd.id', '=', 'ndr.pituitary_drugs_id')
//                        ->leftJoin('z_hosp_member as hm', 'hm.id', '=', 'ndr.op_id') doc_name
                        ->select('ndr.*', 'nd.drug_id' )
                        ->where('nd.is_deleted', 0)
                        ->where("ndr.pituitary_drugs_id", $id)->where("ndr.is_deleted", 0)->offset($offset)
                        ->limit($pageSize)
                        ->orderBy('ndr.id', 'asc')->get()->toArray();
    }

    //点击调整 需要详细的用药记录
    public function getdetailById($id) {
        return ZPituitaryManageDrugs::query()
                        ->from('z_pituitary_manage_drugs as nd')
                        ->leftJoin('z_pituitary_drug as d', 'd.id', '=', 'nd.drug_id')
                        ->leftJoin('z_pituitary_drug_type as dt', 'dt.id', '=', 'd.type_id')
                        ->select('d.general_name', 'd.drug_name', 'd.drug_no', 'd.type_id', 'dt.type_name', 'nd.*')
                        ->where('nd.is_deleted', 0)
                        ->where('nd.id', $id)
                        ->first();
    }

    //获取用户用药信息
    public function getUserDrugList($userId, $categoryId = 1) {

        return ZPituitaryManageDrugs::query()
                        ->from('z_pituitary_manage_drugs as nd')
                        ->leftJoin('z_pituitary_manage_drugs_records as ndr', 'nd.id', '=', 'ndr.pituitary_drugs_id')
                        ->leftJoin('z_pituitary_drug as d', 'd.id', '=', 'nd.drug_id')
                        ->leftJoin('z_pituitary_drug_type as dt', 'dt.id', '=', 'd.type_id')
                        ->select('d.general_name', 'd.drug_name', 'd.drug_no', 'dt.type_name', 'd.type_id', 'dt.pid', 'nd.is_used as used_flag', 'nd.drug_id', 'nd.drug_alias', 'nd.is_expection', 'ndr.*')
                        ->where('nd.is_deleted', 0)
                        ->where('ndr.is_deleted', 0)
                        ->where('nd.user_id', $userId)
                        ->where('dt.type_category', $categoryId)
                        ->orderBy('ndr.id', 'asc')
                        ->get()
                        ->toArray();
    }

}
